package com.ldk.api.handler;

import com.ldk.api.ApiVersion;
import com.ldk.api.CheckToken;
import com.ldk.api.ErrorCode;
import com.ldk.api.RequestPlatform;
import com.ldk.api.ResponseObject;
import com.ldk.api.ResponseResult;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.*;
import com.ldk.framework.enums.PlatformUserType;
import com.ldk.framework.enums.TradePayStatus;
import com.ldk.framework.service.*;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;

import java.util.List;
import java.util.Map;

public class TicketRequestHandler extends BaseRequestHandler {
    @Autowired
    private ITicketUserService ticketUserService;
    @Autowired
    private ITicketLevelService ticketLevelService;
    @Autowired
    private ITicketRelateService ticketRelateService;
    @Autowired
    private IDriverService driverService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRechargeRecordService rechargeRecordService;


    /**
     * 申请成为票务经理
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramstatus 状态: 0 未使用; 1 乘客已使用(司机已提现); -1 已过期
     * @parampageIndex 分页索引
     * @parampageSize 分页每页条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject applyTicketUser(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("ticket", "applyTicketUser");
        //参数检验
        if (!checkRequireParms(parms, "phoneNo", "userName")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        String userName = ConvertUtil.parseString(parms.get("userName"));
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        if (StringUtils.isBlank(userName)) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        TicketUser user = ticketUserService.getTicketInfoByPhoneNo("", phoneNo);
        if (user != null) {
            return ResponseResult.exception(response, ErrorCode.TICKET_PHONE_EXIST);
        }
        TicketUser model = new TicketUser();
        model.setPhoneNo(phoneNo);
        model.setUserName(userName);
        String saleNo = ticketUserService.generateSaleNo("");
        model.setSaleNo(saleNo);
        model.setBalance(0.0);
        model.setCash(0.0);
        model.setIncome(0.0);
        model.setRecNum(0);
        model.setCreateTime(SystemUtil.getAllSeconds());
        model.setEnabled(true);
        //待审核
        model.setState(1);
        //查询等级
        TicketLevel query1 = new TicketLevel();
        query1.setLevel(1);
        TicketLevel ticketLevel = ticketLevelService.selectOne("", query1);
        if (ticketLevel != null) {
            model.setLevel(ticketLevel.getLevel());
            model.setLevelName(ticketLevel.getName());
        } else {
            model.setLevel(1);
            model.setLevelName("黄金票务经理");
        }

        //查询我的上级，上上级
        TicketRelate relate = new TicketRelate();
        relate.setPhoneNo(phoneNo);
        List<TicketRelate> list = ticketRelateService.selectList("", relate);
        if (list != null && list.size() > 0) {
            for (TicketRelate ticketRelate : list) {
                if(ticketRelate.getLevelType()==1){
                    model.setLevel1Phone(ticketRelate.getLevelPhone());
                    model.setLevel1Name(ticketRelate.getLevelName());
                }
                if(ticketRelate.getLevelType()==2){
                    model.setLevel2Phone(ticketRelate.getLevelPhone());
                    model.setLevel1Name(ticketRelate.getLevelName());
                }
            }
        }

        int row = ticketUserService.insert("", model);
        if (row > 0) {
            TicketUser ticketUser1 = ticketUserService.getTicketInfoBySaleNo("", saleNo);
            response = ResponseResult.success(response, ticketUser1);
        } else {
            response = ResponseResult.success(response, "添加失败");
        }
        return response;
    }


    /**
     * 获取我的佣金
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramstatus 状态: 0 未使用; 1 乘客已使用(司机已提现); -1 已过期
     * @parampageIndex 分页索引
     * @parampageSize 分页每页条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject getTicketInfo(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("ticket", "getTicketInfo");
        //参数检验
        if (!checkRequireParms(parms, "phoneNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }

        TicketUser user = ticketUserService.getTicketInfoByPhoneNo("", phoneNo);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.TICKET_USER_NULL);
        }

        response = ResponseResult.success(response, user);
        return response;
    }

    /**
     * 获取我的下级用户
     *
     * @param parms
     * @return
     * @paramphoneNo 手机号
     * @paramlevelType 状态: 1-一级分销  2-二级分销
     * @parampageIndex 分页索引
     * @parampageSize 分页每页条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.client)
    public ResponseObject getSubList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("ticket", "getSubList");
        //参数检验
        if (!checkRequireParms(parms, "phoneNo", "levelType", "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        int levelType = ConvertUtil.parseInt(parms.get("levelType"), 1);

        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);
        int offset = (pageIndex - 1) * pageSize;
        Sort sort = new Sort(Sort.Direction.DESC, "create_time");
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);

        TicketRelate query = new TicketRelate();
        query.setLevelPhone(phoneNo);
        query.setLevelType(levelType);

        List<TicketRelate> result = ticketRelateService.selectList("", query, pageable);

        response = ResponseResult.success(response, result);
        return response;
    }


    /**
     * 获取票务经理收益记录列表
     *
     * @param parms {openId, pageIndex, pageSize}
     * @return
     * @paramopenId 用户openId
     * @parampageIndex 分页索引
     * @parampageSize 分页每页显示条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.client)
    public ResponseObject getTicketRechargeRecordList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "getTicketRechargeRecordList");
        if (!checkRequireParms(parms, "phoneNo", "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String phoneNo = String.valueOf(parms.get("phoneNo"));
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);

        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }

        TicketUser user = ticketUserService.getTicketInfoByPhoneNo("", phoneNo);
        if (user == null) {
            ResponseResult.exception(response, ErrorCode.TICKET_USER_NULL);
        }
        int offset = (pageIndex - 1) * pageSize;
        Sort sort = new Sort(Sort.Direction.DESC, "recharge_time");
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);

        RechargeRecord query = new RechargeRecord();
        query.setPhoneNo(phoneNo);
        query.setUserType(PlatformUserType.TICKET_USER.getValue());

        List<RechargeRecord> result = rechargeRecordService.selectList("", query, pageable);
        if (result == null) {
            ResponseResult.exception(response, ErrorCode.USER_RECHARGE_ORDER_NO_MORE);
        } else {
            ResponseResult.success(response, result);
        }
        return response;
    }
}
